package com.jiuyin.dianjing.ui.fragment.team;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.BaseRecyclerAdapter;
import com.jiuyin.dianjing.adapter.SmartViewHolder;
import com.jiuyin.dianjing.api.base.DefaultApiResult;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.model.Team;
import com.jiuyin.dianjing.ui.activity.team.TeamDetailNewActivity;
import com.jiuyin.dianjing.ui.fragment.base.BaseFragment;
import com.jiuyin.dianjing.ui.fragment.base.BaseRefreshFragment;
import com.jiuyin.dianjing.util.DisplayUtil;
import com.jiuyin.dianjing.util.IMEUtil;
import com.jiuyin.dianjing.util.LogUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import ezy.ui.layout.LoadingLayout;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_GAMEID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_PAGE_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TEAM_LIST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_USER_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_WORD;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_FIRST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_NUM;


public class TeamsFragment extends BaseRefreshFragment<Team> {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "param3";
    private String mGameId;
    private String mWord;
    private boolean mOnlyMine;//是否仅我的战队
    private String mUserId;

    public TeamsFragment() {
        super(PAGE_NUM);
    }

    public static TeamsFragment newInstance(String gameId, String userId, boolean onlyMine) {
        TeamsFragment fragment = new TeamsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, gameId);
        args.putBoolean(ARG_PARAM2, onlyMine);
        args.putString(ARG_PARAM3, userId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void fetchData() {
        HashMap hashMap = new HashMap();
        hashMap.put(KEY_GAMEID, mGameId);
        hashMap.put(KEY_PAGE_NUM, mPageNum);
        hashMap.put(KEY_WORD, mWord);
        hashMap.put(KEY_TOKEN, HelperApplication.getToken());
        if (!TextUtils.isEmpty(mUserId)) {
            hashMap.put(KEY_USER_ID, mUserId);
        }
        JSONObject data = new JSONObject(hashMap);
        ApiResultCallback request = new DefaultApiResult() {
            @Override
            public void onSuccess(JsonObject data) {
                LogUtil.log("TeamsFragment onSuccess " + data.toString());
                if (null != data && data.has(KEY_TEAM_LIST)) {
                    List<Team> competeList = new Gson().fromJson(data.getAsJsonArray(KEY_TEAM_LIST), new TypeToken<List<Team>>() {
                    }.getType());
                    dealWithSuccessInfo(competeList);
                } else {
                    dealOtherInfo();
                }
            }

            @Override
            public void onFail(String msg) {
                dealOtherInfo();
            }

            @Override
            public void onError(String msg) {
                dealOtherInfo();
            }
        };
        ServerApi.post(mOnlyMine ? ApiEnum.MY_TEAM_LIST : ApiEnum.GET_ALL_ALLOW_APPLY_FORTEAM, data, null, progress, null, request);
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_teams;
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        if (getArguments() != null) {
            mGameId = getArguments().getString(ARG_PARAM1);
            mOnlyMine = getArguments().getBoolean(ARG_PARAM2);
            mUserId = getArguments().getString(ARG_PARAM3);
        }
    }

    @Override
    protected void initView() {
        mAdapter = new BaseRecyclerAdapter<Team>(R.layout.item_teams) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, Team model, int position) {
                ImageView ivHead = holder.itemView.findViewById(R.id.iv_head);
                Glide.with(getContext())
                        .load(model.logo)
                        .override(DisplayUtil.dp2px(getContext(), 26.7f))
                        .into(ivHead);
                holder.text(R.id.tv_name, model.name);
                holder.itemView.setOnClickListener(v -> {
                    Intent intent = new Intent(getContext(), TeamDetailNewActivity.class);
                    intent.putExtra("team", model);
                    startActivity(intent);
                    if (getActivity() != null) {
                        IMEUtil.hideInputMethod(getActivity());
                    }
                });
            }
        };
        DividerItemDecoration divider = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        mRcvPage.addItemDecoration(divider);
        mRcvPage.setAdapter(mAdapter);
    }

    public void setWord(String word) {
        mWord = word;
    }

    public void setGameId(String gameId) {
        mGameId = gameId;
    }

    public void refresh() {
        mPageNum = PAGE_FIRST;
        fetchData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshEvent event) {
        if (event.clazzName != null && event.clazzName.equals(getClass().getSimpleName())) {
            mAdapter.clear();
            refresh();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
